﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ZGLXM.Infra
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class, new()
    {
        private readonly BaseDataContext baseDataContext;
        private readonly ILogger<BaseRepository<T>> logger;
        public BaseRepository(BaseDataContext baseDataContext, ILogger<BaseRepository<T>> logger)
        {
            this.baseDataContext = baseDataContext;
            this.logger = logger;
        }

        public async Task<IList<T>> GetAllAsync()
        {
            try
            {
                return await baseDataContext.Set<T>().ToListAsync();
            }
            catch (Exception ex)
            {
                logger.LogError("查询异常" + ex.Message);
                throw;
            }
        }

        public async Task<IList<T>> GetAllAsync(Expression<Func<T, bool>> param)
        {
            try
            {
                return await baseDataContext.Set<T>().Where(param).ToListAsync();
            }
            catch (Exception ex)
            {
                logger.LogError("查询异常" + ex.Message);
                throw;
            }
        }

        public async Task<T?> GetAsync(Expression<Func<T, bool>> param)
        {
            try
            {
                return await baseDataContext.Set<T>().FirstOrDefaultAsync(param);
            }
            catch (Exception ex)
            {
                logger.LogError("查询异常" + ex.Message);
                throw;
            }
        }

        public async Task<int> InsertAsync(T entity)
        {
            try
            {
                await baseDataContext.Set<T>().AddAsync(entity);
                return await baseDataContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                logger.LogError("新增异常" + ex.Message);
                throw;
            }
        }

        public async Task<int> UpdateAsync(T entity)
        {
            try
            {
                baseDataContext.Set<T>().Update(entity);
                return await baseDataContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                logger.LogError("更新异常" + ex.Message);
                throw;
            }
        }
    }
}
